<template>
  <div class="space-y-6">
    <div class="flex items-center justify-between mb-6">
      <h2 :class="[
        'text-2xl font-bold flex items-center',
        themeState.isDark ? 'text-white' : 'text-blue-900'
      ]">
        <BarChart3 class="w-6 h-6 mr-3 text-blue-500" />
        {{ ts('政策对比分析', '政策对比分析') }}
      </h2>
      <div class="flex space-x-3">
        <button 
          @click="generateComparison"
          :disabled="selectedPoliciesForCompare.length < 2 || loadingPolicies"
          class="px-6 py-3 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors disabled:opacity-50 flex items-center"
        >
          <svg v-if="loadingPolicies" class="animate-spin h-4 w-4 mr-2" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none" />
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z" />
          </svg>
          {{ loadingPolicies ? ts('正在获取详细信息...', '正在获取详细信息...') : ts('生成对比报告', '生成对比报告') }}
        </button>
        <button 
          v-if="comparisonResult"
          @click="exportAsImage" 
          :class="[
            'px-4 py-3 rounded-lg transition-colors flex items-center',
            themeState.isDark 
              ? 'bg-gray-600 text-white hover:bg-gray-700' 
              : 'bg-blue-100 text-blue-900 hover:bg-blue-200'
          ]"
        >
          <Download class="w-4 h-4 mr-2 text-blue-500" />
          {{ ts('导出图表', '导出图表') }}
        </button>
      </div>
    </div>
    
    <!-- 政策选择器 -->
    <div class="grid grid-cols-1 gap-6">
      <div>
        <div class="flex items-center justify-between mb-4">
          <h3 :class="[
            'text-lg font-semibold',
            themeState.isDark ? 'text-white' : 'text-blue-900'
          ]">{{ ts('待对比政策', '待对比政策') }}</h3>
          <span v-if="preSelectedFromQuery" class="text-sm text-blue-400">
            {{ ts('已从查询页面导入', '已从查询页面导入') }} {{ selectedPoliciesForCompare.length }} {{ ts('项政策', '项政策') }}
          </span>
          <span v-else class="text-sm text-gray-400">
            {{ ts('当前选中', '当前选中') }} {{ selectedPoliciesForCompare.length }} {{ ts('项政策', '项政策') }}
          </span>
        </div>
        <div class="space-y-3 max-h-96 overflow-y-auto">
          
          <!-- 已选中的政策列表 -->
          <div v-if="comparedPolicies.length > 0">
            <h5 :class="['text-sm font-medium mb-2', themeState.isDark ? 'text-blue-300' : 'text-blue-600']">
              {{ ts('已选中对比', '已选中对比') }} ({{ comparedPolicies.length }})
            </h5>
            <div 
              v-for="policy in comparedPolicies" 
              :key="'selected-' + policy.id"
              :class="[
                'p-4 rounded-lg border mb-2',
                'bg-blue-500/20 border-blue-500',
                themeState.isDark ? 'bg-blue-500/10' : 'bg-blue-100'
              ]"
            >
              <div class="flex items-center justify-between">
                <div class="flex-1 mr-4">
                  <h4 :class="['font-medium', themeState.isDark ? 'text-white' : 'text-gray-900']">
                    {{ policy.title }}
                  </h4>
                </div>
                <div class="flex items-center space-x-2">
                  <span :class="[
                    'px-2 py-1 rounded text-xs',
                    'bg-green-500/20 text-green-400'
                  ]">
                    {{ ts('已选中', '已选中') }}
                  </span>
                  <button 
                    @click="removePolicyFromComparison(policy)"
                    :class="[
                      'p-1 rounded hover:bg-red-500/20 transition-colors',
                      themeState.isDark ? 'text-red-400 hover:text-red-300' : 'text-red-600 hover:text-red-500'
                    ]"
                    :title="ts('移回待选列表', '移回待选列表')"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 待选政策列表 -->
          <div v-if="unselectedPolicies.length > 0">
            <h5 :class="['text-sm font-medium mb-2 mt-4', themeState.isDark ? 'text-gray-300' : 'text-gray-600']">
              {{ ts('待选政策', '待选政策') }} ({{ unselectedPolicies.length }})
            </h5>
            <div 
              v-for="policy in unselectedPolicies" 
              :key="'unselected-' + policy.id"
              :class="[
                'p-4 rounded-lg border mb-2 cursor-pointer transition-colors',
                themeState.isDark 
                  ? 'bg-gray-800/50 border-gray-600 hover:border-blue-500/50 hover:bg-blue-500/5' 
                  : 'bg-gray-50 border-gray-300 hover:border-blue-400 hover:bg-blue-50'
              ]"
              @click="addPolicyToComparison(policy)"
            >
              <div class="flex items-center justify-between">
                <div class="flex-1 mr-4">
                  <h4 :class="['font-medium', themeState.isDark ? 'text-white' : 'text-gray-900']">
                    {{ policy.title }}
                  </h4>
                </div>
                <div class="flex items-center space-x-2">
                  <span :class="[
                    'px-2 py-1 rounded text-xs',
                    themeState.isDark ? 'bg-gray-600/50 text-gray-300' : 'bg-gray-200 text-gray-600'
                  ]">
                    {{ ts('待选择', '待选择') }}
                  </span>
                  <button 
                    @click.stop="addPolicyToComparison(policy)"
                    :class="[
                      'p-1 rounded hover:bg-blue-500/20 transition-colors',
                      themeState.isDark ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-500'
                    ]"
                    :title="ts('选择进行对比', '选择进行对比')"
                  >
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 空状态 - 没有传递政策时 -->
          <div v-if="availablePoliciesFromQuery.length === 0" class="text-center py-8">
            <div :class="themeState.isDark ? 'text-white/70' : 'text-gray-600'">
              <svg class="w-16 h-16 mx-auto mb-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
              <p class="mb-2">{{ ts('暂无传递的政策', '暂无传递的政策') }}</p>
              <p class="text-sm">{{ ts('请先在政策查询页面选择要对比的政策', '请先在政策查询页面选择要对比的政策') }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 对比结果 -->
    <div v-if="comparisonResult && comparedPolicies.length >= 2" class="mt-8 space-y-6">
      <h3 :class="['text-xl font-bold mb-6', themeState.isDark ? 'text-white' : 'text-gray-900']">{{ ts('对比结果', '对比结果') }}</h3>
      
      <!-- 基本信息对比表格 -->
      <div :class="['rounded-lg p-6', themeState.isDark ? 'bg-white/5' : 'bg-blue-50']">
        <h4 :class="['font-medium mb-4', themeState.isDark ? 'text-white' : 'text-gray-900']">{{ ts('基本信息对比', '基本信息对比') }}</h4>
        <div class="overflow-x-auto">
          <table class="w-full text-sm min-w-[600px]">
            <thead>
              <tr :class="['border-b', themeState.isDark ? 'border-white/20' : 'border-gray-300']">
                <th :class="['text-left py-2 w-32', themeState.isDark ? 'text-white/70' : 'text-gray-600']">{{ ts('项目', '项目') }}</th>
                <th v-for="policy in comparedPolicies" :key="policy.id"
                  :class="['text-left py-2 px-2 max-w-[200px] truncate', themeState.isDark ? 'text-white' : 'text-gray-900']" :title="policy.title">
                  {{ policy.title.substring(0, 20) }}{{ policy.title.length > 20 ? '...' : '' }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr :class="['border-b', themeState.isDark ? 'border-white/10' : 'border-gray-200']">
                <td :class="['py-2', themeState.isDark ? 'text-white/70' : 'text-gray-600']">{{ ts('发布部门', '发布部门') }}</td>
                <td v-for="policy in comparedPolicies" :key="policy.id" :class="['py-2 px-2', themeState.isDark ? 'text-white' : 'text-gray-900']">
                  {{ policy.department || '-' }}
                </td>
              </tr>
              <tr :class="['border-b', themeState.isDark ? 'border-white/10' : 'border-gray-200']">
                <td :class="['py-2', themeState.isDark ? 'text-white/70' : 'text-gray-600']">{{ ts('发布时间', '发布时间') }}</td>
                <td v-for="policy in comparedPolicies" :key="policy.id" :class="['py-2 px-2', themeState.isDark ? 'text-white' : 'text-gray-900']">
                  {{ policy.publishDate || '-' }}
                </td>
              </tr>
              <tr :class="['border-b', themeState.isDark ? 'border-white/10' : 'border-gray-200']">
                <td :class="['py-2', themeState.isDark ? 'text-white/70' : 'text-gray-600']">{{ ts('政策类别', '政策类别') }}</td>
                <td v-for="policy in comparedPolicies" :key="policy.id" class="py-2 px-2">
                  <span :class="[
                    'px-2 py-1 rounded text-xs',
                    themeState.isDark 
                      ? 'bg-blue-500/20 text-blue-300' 
                      : 'bg-blue-100 text-blue-700'
                  ]">
                    {{ policy.category || '-' }}
                  </span>
                </td>
              </tr>
              <tr>
                <td :class="['py-2', themeState.isDark ? 'text-white/70' : 'text-gray-600']">{{ ts('当前状态', '当前状态') }}</td>
                <td v-for="policy in comparedPolicies" :key="policy.id" class="py-2 px-2">
                  <span :class="getStatusClass(policy.status)">
                    {{ getStatusText(policy.status) || '-' }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 影响范围对比图表 -->
      <div :class="['rounded-lg p-6', themeState.isDark ? 'bg-white/5' : 'bg-blue-50']">
        <div class="flex items-center justify-between mb-4">
          <h4 :class="['font-medium', themeState.isDark ? 'text-white' : 'text-gray-900']">{{ ts('影响范围对比', '影响范围对比') }}</h4>
          <div class="flex space-x-2">
            <button 
              v-for="(preset, key) in chartPresets" 
              :key="key" 
              @click="currentChartType = key"
              :class="[
                'px-3 py-1 rounded text-sm transition-colors',
                currentChartType === key 
                  ? 'bg-blue-500 text-white' 
                  : themeState.isDark 
                    ? 'bg-gray-600 text-gray-300 hover:bg-gray-500'
                    : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
              ]"
            >
              {{ preset.title }}
            </button>
          </div>
        </div>
        <div :class="['h-64 rounded-lg', themeState.isDark ? 'bg-gray-800/50' : 'bg-gray-100']">
          <!-- ECharts 对比图表 -->
          <v-chart 
            v-if="chartData"
            :option="chartOption" 
            :theme="themeState.isDark ? 'dark' : 'light'"
            autoresize
            class="w-full h-full"
          />
          <!-- 无数据时的占位符 -->
          <div v-else class="flex items-center justify-center h-full">
            <div class="text-center">
              <BarChart3 class="w-16 h-16 text-blue-500 mx-auto mb-4" />
              <p :class="themeState.isDark ? 'text-white/70' : 'text-gray-600'">{{ ts('选择政策后将显示对比图表', '选择政策后将显示对比图表') }}</p>
              <p :class="['text-sm mt-2', themeState.isDark ? 'text-white/50' : 'text-gray-500']">{{ ts('当前图表类型', '当前图表类型') }}: {{ chartPresets[currentChartType].title }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 智能对比分析 -->
      <div :class="['rounded-lg p-6', themeState.isDark ? 'bg-white/5' : 'bg-blue-50']">
        <div class="flex items-center justify-between mb-4">
          <h4 :class="['font-medium flex items-center', themeState.isDark ? 'text-white' : 'text-blue-900']">
            <span class="mr-2">🤖</span>
            {{ ts('智能对比分析', '智能对比分析') }}
          </h4>
          <button 
            @click="analyzeWithAI"
            :disabled="aiLoading"
            class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors disabled:opacity-50"
          >
            {{ aiLoading ? ts('分析中...', '分析中...') : ts('生成智能分析', '生成智能分析') }}
          </button>
        </div>

        <div v-if="aiLoading" :class="['py-4 flex items-center', themeState.isDark ? 'text-blue-500' : 'text-blue-600']">
          <svg class="animate-spin h-5 w-5 mr-2" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none" />
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z" />
          </svg>
          {{ ts('正在调用AI分析，请稍候...', '正在调用AI分析，请稍候...') }}
        </div>

        <div v-if="aiError" :class="['py-2', themeState.isDark ? 'text-red-400' : 'text-red-600']">{{ aiError }}</div>

        <div v-if="aiResult" :class="['ai-analysis-content p-4 rounded-lg mt-2 whitespace-pre-line', themeState.isDark ? 'bg-[#1a2236] text-white/90' : 'bg-white text-blue-900 border border-blue-200']">
          <div v-html="aiResultHtml" class="ai-result-html"></div>
          <div class="mt-4 flex space-x-2">
            <button @click="copyAIAnalysis" class="cyber-button-sm">
              <Copy class="w-4 h-4 mr-1 text-blue-500" /> {{ ts('复制内容', '复制内容') }}
            </button>
            <button @click="exportAIAnalysis('txt')" class="cyber-button-sm">
              <FileTextIcon class="w-4 h-4 mr-1 text-blue-500" /> {{ ts('导出TXT', '导出TXT') }}
            </button>
            <button @click="exportAIAnalysis('image')" class="cyber-button-sm">
              <Download class="w-4 h-4 mr-1 text-blue-500" /> {{ ts('导出图片', '导出图片') }}
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 未选择政策时的提示 -->
    <div v-else-if="selectedPoliciesForCompare.length < 2" class="mt-8">
      <div :class="['rounded-lg p-8 text-center', themeState.isDark ? 'bg-white/5' : 'bg-blue-50']">
        <BarChart3 class="w-16 h-16 text-blue-500 mx-auto mb-4" />
        <h4 :class="['font-medium mb-2', themeState.isDark ? 'text-white' : 'text-gray-900']">{{ ts('请选择至少2项政策进行对比', '请选择至少2项政策进行对比') }}</h4>
        <p :class="['text-sm', themeState.isDark ? 'text-white/70' : 'text-gray-600']">{{ ts('选择您感兴趣的政策，我们将为您生成详细的对比分析报告', '选择您感兴趣的政策，我们将为您生成详细的对比分析报告') }}</p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useTranslation } from '../composables/useTranslation.js'
import { themeState } from '../services/themeService.js'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { RadarChart, LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import {
  BarChart3,
  Download,
  Copy,
  FileText as FileTextIcon
} from 'lucide-vue-next'

// 注册ECharts组件
use([
  CanvasRenderer,
  RadarChart,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

export default {
  name: 'PolicyCompare',
  components: {
    BarChart3,
    Download,
    Copy,
    FileTextIcon,
    VChart
  },
  
  setup() {
    const { ts } = useTranslation()
    const route = useRoute()
    
    // 响应式状态
    const selectedPoliciesForCompare = ref([])
    const availablePoliciesFromQuery = ref([]) // 从查询页传来的所有政策
    const preSelectedFromQuery = ref(false)
    const comparisonResult = ref(null)
    const currentChartType = ref('impact')
    const aiLoading = ref(false)
    const aiError = ref(null)
    const aiResult = ref(null)
    const loadingPolicies = ref(false)
    
    // 新增：真实政策数据存储
    const realPolicyData = ref([])
    const policyStatistics = ref(null)
    const policyGeoData = ref(null)
    
    // Markdown渲染器
    const md = new MarkdownIt({ 
      html: true, 
      linkify: true, 
      breaks: true,
      typographer: true
    })
    
    // 静态数据 - 更新图表预设，包含地理分布
    const chartPresets = {
      impact: { title: '特征对比', type: 'radar' },
      time: { title: '时间线', type: 'line' },
      geo: { title: '地理分布', type: 'bar' },
      type: { title: '类型分布', type: 'pie' }
    }
    
    // 动态加载的政策数据
    const availablePolicies = ref([])
    
    // 计算属性 - 修复政策显示逻辑
    const comparedPolicies = computed(() => {
      // 首先从realPolicyData中查找（用于生成对比报告后的详细信息）
      const realDataPolicies = realPolicyData.value.filter(policy => 
        selectedPoliciesForCompare.value.includes(String(policy.policyId))
      )
      
      // 如果realPolicyData中没有数据，使用availablePoliciesFromQuery中的基本信息
      if (realDataPolicies.length === 0) {
        return availablePoliciesFromQuery.value.filter(policy => 
          selectedPoliciesForCompare.value.includes(String(policy.id))
        )
      }
      
      return realDataPolicies
    })
    
    // 待选政策（从查询页传来但未选中的）
    const unselectedPolicies = computed(() => {
      return availablePoliciesFromQuery.value.filter(policy => 
        !selectedPoliciesForCompare.value.some(id => String(id) === String(policy.id))
      )
    })
    
    const aiResultHtml = computed(() => {
      if (!aiResult.value) return ''
      
      let html = md.render(aiResult.value)
      
      // 清理空的表格行和单元格
      html = html.replace(/<tr>\s*<td[^>]*>\s*<\/td>\s*<\/tr>/g, '')
      html = html.replace(/<tr>\s*(<td[^>]*>\s*<\/td>\s*){1,10}<\/tr>/g, (match) => {
        // 如果整行都是空单元格，则删除
        const emptyCheck = match.replace(/<\/?t[rd][^>]*>/g, '').trim()
        return emptyCheck === '' ? '' : match
      })
      
      // 根据主题动态调整表格样式
      if (themeState.isDark) {
        html = html.replace(
          /<table[^>]*>/g, 
          '<table style="width: 100%; border-collapse: collapse; margin: 1rem 0; border: 2px solid rgba(168, 85, 247, 0.5);">'
        )
        html = html.replace(
          /<th[^>]*>/g, 
          '<th style="border: 1px solid rgba(168, 85, 247, 0.5); padding: 0.75rem 1rem; background: rgba(168, 85, 247, 0.25); color: #c084fc; font-weight: 600; text-align: left;">'
        )
        html = html.replace(
          /<td[^>]*>/g, 
          '<td style="border: 1px solid rgba(168, 85, 247, 0.4); padding: 0.75rem 1rem; background: rgba(30, 41, 59, 0.7); color: #e5e7eb; text-align: left;">'
        )
      } else {
        html = html.replace(
          /<table[^>]*>/g, 
          '<table style="width: 100%; border-collapse: collapse; margin: 1rem 0; border: 2px solid rgba(168, 85, 247, 0.4);">'
        )
        html = html.replace(
          /<th[^>]*>/g, 
          '<th style="border: 1px solid rgba(168, 85, 247, 0.4); padding: 0.75rem 1rem; background: rgba(168, 85, 247, 0.15); color: #7c3aed; font-weight: 600; text-align: left;">'
        )
        html = html.replace(
          /<td[^>]*>/g, 
          '<td style="border: 1px solid rgba(168, 85, 247, 0.3); padding: 0.75rem 1rem; background: #ffffff; color: #374151; text-align: left;">'
        )
      }
      
      return html
    })
    
    // 新增：计算覆盖范围得分
    // 地址层级：address1(国家) -> address2(省份) -> address3(盟市) -> address4(区县) -> address5 -> address6(最细分)
    const calculateCoverageScore = (policy) => {
      let score = 0
      if (policy.address1) score += 15  // 国家级
      if (policy.address2) score += 20  // 省份级  
      if (policy.address3) score += 15  // 盟市级
      if (policy.address4) score += 15  // 区县级
      if (policy.address5) score += 10  // 更细分级别
      if (policy.address6) score += 15  // 最细分级别
      if (policy.isCompanyPolicy) score += 5
      if (policy.isCrossborderPolicy) score += 5
      return Math.min(score, 100)
    }
    
    // 新增：计算实施复杂度得分
    const calculateComplexityScore = (policy) => {
      let score = 50 // 基础分
      if (policy.level && policy.level > 3) score += 20
      if (policy.isCrossborderPolicy) score += 15
      if (policy.isCompanyPolicy) score += 10
      if (policy.mainText && policy.mainText.length > 10000) score += 5
      return Math.min(score, 100)
    }
    
    // 新增：计算时效性得分
    const calculateTimelinessScore = (policy) => {
      const now = new Date()
      const publishDate = policy.publishTime ? new Date(policy.publishTime) : null
      const startDate = policy.startTime ? new Date(policy.startTime) : null
      const endDate = policy.endTime ? new Date(policy.endTime) : null
      
      let score = 50
      
      if (publishDate) {
        const daysSincePublish = (now - publishDate) / (1000 * 60 * 60 * 24)
        if (daysSincePublish < 30) score += 30
        else if (daysSincePublish < 90) score += 20
        else if (daysSincePublish < 365) score += 10
      }
      
      if (policy.validity) score += 20
      
      return Math.min(score, 100)
    }
    
    // 新增：计算时间线进度
    const calculateTimelineProgress = (policy) => {
      const now = new Date()
      const writeDate = policy.writeTime ? new Date(policy.writeTime) : null
      const publishDate = policy.publishTime ? new Date(policy.publishTime) : null
      const startDate = policy.startTime ? new Date(policy.startTime) : null
      const endDate = policy.endTime ? new Date(policy.endTime) : null
      
      const progress = [0, 0, 0, 0, 0] // 起草、发布、生效、实施、评估
      
      if (writeDate && now >= writeDate) progress[0] = 100
      if (publishDate && now >= publishDate) progress[1] = 100
      if (startDate && now >= startDate) progress[2] = 100
      
      // 实施阶段根据当前时间和生效时间计算
      if (startDate && now >= startDate) {
        if (endDate) {
          const totalDuration = endDate - startDate
          const elapsed = now - startDate
          progress[3] = Math.min((elapsed / totalDuration) * 100, 100)
        } else {
          progress[3] = 80 // 无结束时间，假设在实施中
        }
      }
      
      // 评估阶段
      if (endDate && now >= endDate) progress[4] = 100
      else if (progress[3] > 50) progress[4] = 30 // 实施过半开始评估
      
      return progress
    }

    // 图表数据 - 基于真实数据
    const chartData = computed(() => {
      if (comparedPolicies.value.length < 2) return null
      
      if (currentChartType.value === 'impact') {
        // 基于政策级别、类型等真实数据的雷达图
        return {
          type: 'radar',
          policies: comparedPolicies.value,
          dimensions: ['政策级别', '覆盖范围', '实施复杂度', '法规完备性', '时效性', '跨境影响']
        }
      } else if (currentChartType.value === 'time') {
        // 基于真实时间数据的时间线
        return {
          type: 'line',
          policies: comparedPolicies.value,
          timeline: ['起草', '发布', '生效', '实施', '评估']
        }
      } else if (currentChartType.value === 'geo') {
        // 基于地址数据的地理分布
        return {
          type: 'bar',
          policies: comparedPolicies.value,
          geoData: policyGeoData.value
        }
      } else if (currentChartType.value === 'type') {
        // 政策类型分布饼图
        return {
          type: 'pie',
          policies: comparedPolicies.value,
          statistics: policyStatistics.value
        }
      }
      
      return null
    })
    
    // ECharts配置 - 使用真实数据
    const chartOption = computed(() => {
      if (!chartData.value) return null
      
      if (chartData.value.type === 'radar') {
        return {
          title: {
            text: '政策特征对比分析',
            textStyle: {
              color: themeState.isDark ? '#ffffff' : '#374151'
            }
          },
          legend: {
            data: chartData.value.policies.map(p => p.title?.substring(0, 15) + '...'),
            textStyle: {
              color: themeState.isDark ? '#ffffff' : '#374151'
            }
          },
          radar: {
            indicator: chartData.value.dimensions.map(dim => ({
              name: dim,
              max: 100
            })),
            nameGap: 20,
            axisName: {
              color: themeState.isDark ? '#e5e7eb' : '#6b7280'
            },
            splitLine: {
              lineStyle: {
                color: themeState.isDark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)'
              }
            },
            axisLine: {
              lineStyle: {
                color: themeState.isDark ? 'rgba(255,255,255,0.2)' : 'rgba(0,0,0,0.2)'
              }
            }
          },
          series: [{
            type: 'radar',
            data: chartData.value.policies.map((policy, index) => ({
              value: [
                policy.level ? policy.level * 20 : 60, // 政策级别
                calculateCoverageScore(policy), // 覆盖范围
                calculateComplexityScore(policy), // 实施复杂度
                policy.validity ? 90 : 50, // 法规完备性
                calculateTimelinessScore(policy), // 时效性
                policy.isCrossborderPolicy ? 80 : 40 // 跨境影响
              ],
              name: policy.title?.substring(0, 15) + '...',
              itemStyle: {
                color: ['#a855f7', '#06b6d4', '#10b981', '#f59e0b'][index % 4]
              }
            }))
          }]
        }
      } else if (chartData.value.type === 'line') {
        return {
          title: {
            text: '政策生命周期对比',
            textStyle: {
              color: themeState.isDark ? '#ffffff' : '#374151'
            }
          },
          xAxis: {
            type: 'category',
            data: chartData.value.timeline,
            axisLabel: {
              color: themeState.isDark ? '#e5e7eb' : '#6b7280'
            }
          },
          yAxis: {
            type: 'value',
            name: '进度(%)',
            axisLabel: {
              color: themeState.isDark ? '#e5e7eb' : '#6b7280'
            }
          },
          legend: {
            data: chartData.value.policies.map(p => p.title?.substring(0, 15) + '...'),
            textStyle: {
              color: themeState.isDark ? '#ffffff' : '#374151'
            }
          },
          series: chartData.value.policies.map((policy, index) => ({
            name: policy.title?.substring(0, 15) + '...',
            type: 'line',
            data: calculateTimelineProgress(policy),
            itemStyle: {
              color: ['#a855f7', '#06b6d4', '#10b981', '#f59e0b'][index % 4]
            }
          }))
        }
      } else if (chartData.value.type === 'bar') {
        // 地理分布柱状图 - 优先显示有数据的最细分层级
        const geoData = chartData.value.geoData || {}
        
        // 按优先级选择显示的地理分布数据
        let distributionData = {}
        let levelName = '地理'
        
        if (Object.keys(geoData.district_distribution || {}).length > 0) {
          distributionData = geoData.district_distribution
          levelName = '区县'
        } else if (Object.keys(geoData.city_distribution || {}).length > 0) {
          distributionData = geoData.city_distribution
          levelName = '盟市'
        } else if (Object.keys(geoData.province_distribution || {}).length > 0) {
          distributionData = geoData.province_distribution
          levelName = '省份'
        } else if (Object.keys(geoData.country_distribution || {}).length > 0) {
          distributionData = geoData.country_distribution
          levelName = '国家'
        } else if (Object.keys(geoData.address6_distribution || {}).length > 0) {
          distributionData = geoData.address6_distribution
          levelName = '详细地址'
        } else if (Object.keys(geoData.address5_distribution || {}).length > 0) {
          distributionData = geoData.address5_distribution
          levelName = '地址'
        }
        
        return {
          title: {
            text: `政策${levelName}分布`,
            textStyle: {
              color: themeState.isDark ? '#ffffff' : '#374151'
            }
          },
          xAxis: {
            type: 'category',
            data: Object.keys(distributionData),
            axisLabel: {
              color: themeState.isDark ? '#e5e7eb' : '#6b7280',
              rotate: Object.keys(distributionData).length > 5 ? 45 : 0  // 标签过多时旋转
            }
          },
          yAxis: {
            type: 'value',
            name: '政策数量',
            axisLabel: {
              color: themeState.isDark ? '#e5e7eb' : '#6b7280'
            }
          },
          series: [{
            type: 'bar',
            data: Object.values(distributionData),
            itemStyle: {
              color: '#a855f7'
            }
          }]
        }
      } else if (chartData.value.type === 'pie') {
        // 政策类型分布饼图
        const typeDistribution = chartData.value.statistics?.type_distribution || {}
        return {
          title: {
            text: '政策类型分布',
            textStyle: {
              color: themeState.isDark ? '#ffffff' : '#374151'
            }
          },
          series: [{
            type: 'pie',
            radius: '70%',
            data: Object.entries(typeDistribution).map(([type, count]) => ({
              name: type,
              value: count
            })),
            itemStyle: {
              borderWidth: 2,
              borderColor: themeState.isDark ? '#1f2937' : '#ffffff'
            }
          }]
        }
      }
      
      return null
    })
    
    // 方法
    const togglePolicySelection = (policy) => {
      const policyId = String(policy.id)
      const index = selectedPoliciesForCompare.value.findIndex(id => String(id) === policyId)
      if (index > -1) {
        selectedPoliciesForCompare.value.splice(index, 1)
        console.log('取消选择政策:', policy.title)
      } else {
        if (selectedPoliciesForCompare.value.length < 4) {
          selectedPoliciesForCompare.value.push(policy.id)
          console.log('选择政策:', policy.title)
        } else {
          console.log('最多只能选择4项政策进行对比')
        }
      }
      console.log('当前选中政策数量:', selectedPoliciesForCompare.value.length)
    }
    
    // 新增：从对比列表中移除政策（移回待选列表）
    const removePolicyFromComparison = (policy) => {
      const policyId = String(policy.id)
      const index = selectedPoliciesForCompare.value.findIndex(id => String(id) === policyId)
      if (index > -1) {
        selectedPoliciesForCompare.value.splice(index, 1)
        console.log('从对比列表中移除政策:', policy.title, '，已移回待选列表')
        console.log('剩余对比政策数量:', selectedPoliciesForCompare.value.length)
        
        // 如果移除后少于2个政策，清除对比结果
        if (selectedPoliciesForCompare.value.length < 2) {
          comparisonResult.value = null
          aiResult.value = null
          aiError.value = null
          console.log('政策数量不足，已清除对比结果')
        }
      }
    }
    
    // 新增：从待选列表中选择政策
    const addPolicyToComparison = (policy) => {
      const policyId = String(policy.id)
      if (!selectedPoliciesForCompare.value.some(id => String(id) === policyId)) {
        if (selectedPoliciesForCompare.value.length < 4) {
          selectedPoliciesForCompare.value.push(policy.id)
          console.log('选择政策进行对比:', policy.title)
          console.log('当前对比政策数量:', selectedPoliciesForCompare.value.length)
        } else {
          console.log('最多只能选择4项政策进行对比')
        }
      }
    }
    
    // 修改：生成对比报告 - 获取真实数据
    const generateComparison = async () => {
      if (selectedPoliciesForCompare.value.length >= 2) {
        try {
          loadingPolicies.value = true
          
          console.log('开始获取政策详细信息和统计数据...')
          
          // 获取政策详细信息
          const response = await axios.post('/api/policy/batch', selectedPoliciesForCompare.value)
          realPolicyData.value = response.data || []
          
          // 获取统计信息
          const statsResponse = await axios.post('/api/policy/statistics', selectedPoliciesForCompare.value)
          policyStatistics.value = statsResponse.data
          
          // 获取地理分布数据
          const geoResponse = await axios.post('/api/policy/geo-distribution', selectedPoliciesForCompare.value)
          policyGeoData.value = geoResponse.data
          
          console.log('真实政策数据:', realPolicyData.value)
          console.log('统计数据:', policyStatistics.value)
          console.log('地理分布数据:', policyGeoData.value)
          
          // 生成对比结果
          comparisonResult.value = {
            id: Date.now(),
            policies: selectedPoliciesForCompare.value,
            timestamp: new Date().toISOString(),
            realData: realPolicyData.value,
            statistics: policyStatistics.value,
            geoData: policyGeoData.value
          }
          
          console.log('对比报告生成成功，使用真实数据')
        } catch (error) {
          console.error('生成对比报告失败:', error)
        } finally {
          loadingPolicies.value = false
        }
      }
    }
    
    const getStatusClass = (status) => {
      const classes = {
        active: 'bg-green-500/20 text-green-400',
        expired: 'bg-red-500/20 text-red-400',
        draft: 'bg-yellow-500/20 text-yellow-400'
      }
      return `px-2 py-1 rounded text-xs ${classes[status] || 'bg-gray-500/20 text-gray-400'}`
    }
    
    const getStatusText = (validity, endTime, startTime) => {
      if (!validity) return '无效'
      
      const now = new Date()
      const end = endTime ? new Date(endTime) : null
      const start = startTime ? new Date(startTime) : null
      
      if (end && now > end) return '已过期'
      if (start && now < start) return '未生效'
      if (start && now >= start) return '生效中'
      
      return '有效'
    }
    
    const exportAsImage = async () => {
      try {
        // 动态导入html2canvas
        const html2canvas = (await import('html2canvas')).default
        
        // 查找图表容器
        const chartContainer = document.querySelector('.v-chart')
        if (!chartContainer) {
          console.warn('未找到图表容器')
          return
        }
        
        // 生成图片
        const canvas = await html2canvas(chartContainer, {
          backgroundColor: themeState.isDark ? '#1f2937' : '#ffffff',
          scale: 2 // 提高清晰度
        })
        
        // 下载图片
        const link = document.createElement('a')
        link.download = `政策对比图表_${new Date().toISOString().slice(0, 10)}.png`
        link.href = canvas.toDataURL()
        link.click()
        
        console.log('图表导出成功')
      } catch (error) {
        console.error('导出图表失败:', error)
      }
    }
    
    // 修改：AI分析 - 传递真实数据
    const analyzeWithAI = async () => {
      if (aiLoading.value) return
      aiLoading.value = true
      aiError.value = null
      
      try {
        const requestData = {
          policies: comparedPolicies.value.map(policy => ({
            id: policy.policyId,
            title: policy.title,
            department: policy.department,
            publish_date: policy.publishTime,
            start_date: policy.startTime,
            end_date: policy.endTime,
            validity: policy.validity,
            type: policy.type,
            level: policy.level,
            is_company_policy: policy.isCompanyPolicy,
            is_crossborder_policy: policy.isCrossborderPolicy,
            addresses: [policy.address1, policy.address2, policy.address3, policy.address4, policy.address5, policy.address6].filter(Boolean),
            content_length: policy.mainText ? policy.mainText.length : 0,
            tags: policy.tags || []
          })),
          statistics: policyStatistics.value,
          geo_data: policyGeoData.value,
          lang: 'zh'
        }
        
        console.log('发送包含真实数据的AI对比分析请求:', requestData)
        
        const response = await fetch('/api/ai/policy/compare', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        })
        
        if (response.ok) {
          const result = await response.json()
          console.log('AI分析返回结果:', result)
          
          if (result && result.success !== false) {
            aiResult.value = result.result || result.comparison || result.analysis || result.data || '分析完成，但未返回具体内容'
          } else {
            aiError.value = result.error || '后端分析失败'
          }
        } else {
          aiError.value = `HTTP错误: ${response.status}`
        }
      } catch (error) {
        console.error('AI分析请求失败:', error)
        aiError.value = 'AI分析失败: ' + (error.message || error)
      } finally {
        aiLoading.value = false
      }
    }
    
    const copyAIAnalysis = () => {
      if (aiResult.value) {
        const el = document.createElement('textarea')
        el.value = stripHtml(aiResult.value)
        document.body.appendChild(el)
        el.select()
        document.execCommand('copy')
        document.body.removeChild(el)
        console.log('复制成功')
      }
    }
    
    const exportAIAnalysis = async (type) => {
      if (!aiResult.value) return
      
      const timestamp = new Date().toISOString().slice(0, 10)
      const filename = `政策智能分析_${timestamp}`
      
      if (type === 'image') {
        try {
          // 动态导入html2canvas
          const html2canvas = (await import('html2canvas')).default
          
          // 查找AI分析结果内容容器（只包含内容，不包含按钮）
          const contentContainer = document.querySelector('.ai-result-html')
          if (!contentContainer) {
            console.warn('未找到AI分析结果内容容器')
            return
          }
          
          // 生成图片 - 只捕获内容区域
          const canvas = await html2canvas(contentContainer, {
            backgroundColor: themeState.isDark ? '#1a2236' : '#ffffff',
            scale: 2, // 提高清晰度
            useCORS: true,
            allowTaint: true,
            width: contentContainer.scrollWidth,
            height: contentContainer.scrollHeight
          })
          
          // 下载图片
          const link = document.createElement('a')
          link.download = `${filename}.png`
          link.href = canvas.toDataURL('image/png')
          link.click()
          
          console.log('图片导出成功')
        } catch (error) {
          console.error('图片导出失败:', error)
          alert('图片导出失败，请稍后重试')
        }
      } else {
        // TXT导出
        const content = stripHtml(aiResult.value)
        const blob = new Blob([content], { type: 'text/plain;charset=utf-8' })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = `${filename}.txt`
        link.click()
        URL.revokeObjectURL(link.href)
        console.log('TXT导出成功')
      }
    }
    
    const stripHtml = (html) => {
      return html.replace(/<[^>]*>/g, '')
    }
    
    // 修改：不再需要加载所有可用政策，只处理预选政策
    const loadAvailablePolicies = async () => {
      // 由于我们只显示预选政策，不再需要加载全部可用政策列表
      console.log('PolicyCompare组件：只显示预选政策，跳过加载全部政策列表')
      return Promise.resolve()
    }
    
    // 新增：根据ID从后端获取单个政策详情
    const fetchPolicyById = async (id) => {
      try {
        console.log('从后端API获取政策详情, ID:', id)
        const response = await axios.get(`/api/policy/${id}`)
        
        if (response.data) {
          const policy = {
            ...response.data,
            id: response.data.id || response.data.policyId || response.data.uuid || id,
            title: response.data.title || response.data.policyTitle || `政策 ${id}`,
            category: response.data.category || response.data.policyType || '未知类别',
            department: response.data.department || response.data.publishDepartment || '未知部门',
            region: response.data.region || response.data.area || '未知地区',
            publishDate: response.data.publishDate || response.data.releaseDate || '2024-01-01',
            summary: response.data.summary || response.data.description || `政策 ${id} 的摘要信息`,
            status: response.data.status || 'active',
            statusText: response.data.statusText || inferPolicyStatus(response.data)
          }
          console.log('成功获取政策详情:', policy.title)
          return policy
        } else {
          console.warn('政策详情API返回空数据, ID:', id)
          return createFallbackPolicy(id)
        }
      } catch (error) {
        console.error('获取政策详情失败, ID:', id, error)
        return createFallbackPolicy(id)
      }
    }
    
    // 新增：创建备用政策对象
    const createFallbackPolicy = (id) => {
      return {
        id: id,
        title: `政策文件 ${id}`,
        category: '政策文件',
        department: '相关部门',
        region: '全国',
        publishDate: '2024-01-01',
        summary: `这是政策文件 ${id} 的基本信息`,
        status: 'active',
        statusText: '生效中'
      }
    }
    
    // 新增：推断政策状态
    const inferPolicyStatus = (policy) => {
      const now = new Date()
      const publishDate = policy.publishDate ? new Date(policy.publishDate) : null
      const effectiveDate = policy.effectiveDate ? new Date(policy.effectiveDate) : null
      const expiryDate = policy.expiryDate ? new Date(policy.expiryDate) : null
      
      // 已过期
      if (expiryDate && now >= expiryDate) return '已过期'
      
      // 生效中
      if (effectiveDate && now >= effectiveDate) return '生效中'
      
      // 即将生效
      if (publishDate && effectiveDate && now >= publishDate && now < effectiveDate) return '即将生效'
      
      // 草案
      if (publishDate && now < publishDate) return '草案'
      
      // 默认状态
      if (publishDate && now >= publishDate) return '生效中'
      
      return '草案'
    }
    
    const loadPreSelectedPolicies = async () => {
      // 首先检查sessionStorage（优先，因为包含完整的政策信息）
      const preSelected = sessionStorage.getItem('preSelectedPolicies')
      if (preSelected) {
        try {
          const policies = JSON.parse(preSelected)
          console.log('从sessionStorage加载预选政策:', policies)
          
          // 直接使用sessionStorage中的政策数据（来自查询页面）
          const validPolicies = policies.map(policy => ({
            id: policy.id || policy.policyId,
            title: policy.title || policy.policyTitle || `政策 ${policy.id}`,
            category: policy.category || '政策文件',
            department: policy.department || '相关部门',
            region: policy.region || '全国',
            publishDate: null, // 不显示发布时间
            summary: null, // 不显示摘要
            status: policy.status || 'active',
            statusText: policy.statusText || '生效中',
            isLoading: false // 已有完整数据
          }))
          
          validPolicies.forEach(policy => {
            if (!availablePolicies.value.find(p => String(p.id) === String(policy.id))) {
              availablePolicies.value.push(policy)
            }
          })
          
          // 同时添加到从查询页传来的政策列表
          availablePoliciesFromQuery.value = [...validPolicies]
          
          selectedPoliciesForCompare.value = validPolicies.map(p => p.id)
          preSelectedFromQuery.value = true
          
          sessionStorage.removeItem('preSelectedPolicies')
          
          console.log('已从sessionStorage加载预选政策，数量:', selectedPoliciesForCompare.value.length)
          return true
        } catch (error) {
          console.error('加载预选政策失败:', error)
        }
      }
      
      // 然后检查路由查询参数（作为备用）
      if (route.query.selectedIds) {
        try {
          const selectedIds = route.query.selectedIds.split(',').map(id => id.trim()).filter(Boolean)
          console.log('从路由查询参数获取的政策IDs:', selectedIds)
          
          // 创建基本政策对象，标题显示为"政策文件"
          const routePolicies = selectedIds.map(id => ({
            id: id,
            title: '政策文件', // 简洁的默认标题
            category: '政策文件',
            department: '相关部门',
            region: '全国',
            publishDate: null,
            summary: null,
            status: 'active',
            statusText: '生效中',
            isLoading: false
          }))
          
          console.log('创建的基本政策对象:', routePolicies)
          
          // 添加这些政策到可用政策列表中
          routePolicies.forEach(policy => {
            if (!availablePolicies.value.find(p => String(p.id) === String(policy.id))) {
              availablePolicies.value.push(policy)
            }
          })
          
          // 同时添加到从查询页传来的政策列表
          availablePoliciesFromQuery.value = [...routePolicies]
          
          selectedPoliciesForCompare.value = routePolicies.map(p => p.id)
          preSelectedFromQuery.value = true
          
          console.log('已从路由查询参数创建基本政策对象，数量:', selectedPoliciesForCompare.value.length)
          return true
        } catch (error) {
          console.error('解析路由查询参数失败:', error)
        }
      }
      
      return false
    }
    
    // 页面挂载时加载数据
    onMounted(async () => {
      console.log('PolicyCompare组件挂载，开始初始化数据...')
      
      // 直接加载预选政策基本信息
      const hasPreSelected = await loadPreSelectedPolicies()
      
      if (!hasPreSelected) {
        console.log('未找到预选政策数据')
      } else {
        console.log('政策对比页面准备就绪，共', selectedPoliciesForCompare.value.length, '项政策')
      }
    })
    
    // 监听图表类型变化，重新生成图表数据
    watch([currentChartType, selectedPoliciesForCompare], () => {
      // 图表数据会自动通过computed属性更新
    }, { deep: true })
    
    return {
      ts,
      themeState,
      selectedPoliciesForCompare,
      availablePoliciesFromQuery,
      preSelectedFromQuery,
      comparisonResult,
      currentChartType,
      aiLoading,
      aiError,
      aiResult,
      chartPresets,
      availablePolicies,
      loadingPolicies,
      realPolicyData,
      policyStatistics,
      policyGeoData,
      comparedPolicies,
      unselectedPolicies,
      aiResultHtml,
      chartData,
      chartOption,
      calculateCoverageScore,
      calculateComplexityScore,
      calculateTimelinessScore,
      calculateTimelineProgress,
      togglePolicySelection,
      removePolicyFromComparison,
      addPolicyToComparison,
      generateComparison,
      getStatusClass,
      getStatusText,
      exportAsImage,
      analyzeWithAI,
      copyAIAnalysis,
      exportAIAnalysis,
      stripHtml,
      loadAvailablePolicies,
      fetchPolicyById,
      createFallbackPolicy,
      inferPolicyStatus
    }
  }
}
</script>

<style scoped>
.glass-card {
  background: rgba(30, 64, 175, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(59, 130, 246, 0.18);
  border-radius: 16px;
}
.theme-light .glass-card {
  --glass-bg: rgba(255,255,255,0.85);
  --glass-border: rgba(0,115,230,0.12);
  --glass-shadow: rgba(0,115,230,0.08);
  color: #222;
}
.theme-light .cyber-button {
  background: linear-gradient(135deg, rgba(0,115,230,0.08), rgba(0,245,255,0.08));
  border: 1px solid rgba(0,115,230,0.18);
  color: #0073e6;
}
.theme-light .cyber-button:hover:not(:disabled) {
  background: linear-gradient(135deg, rgba(0,115,230,0.15), rgba(0,245,255,0.15));
  box-shadow: 0 0 12px rgba(0,115,230,0.12);
}
.theme-light .status-info {
  background-color: rgba(59,130,246,0.12);
  color: #2563eb;
}

/* 对比功能表格样式 */
table {
  border-collapse: collapse !important;
  width: 100% !important;
}

/* 隐藏空行和空单元格 */
.ai-analysis-content tr:empty,
.ai-result-html tr:empty {
  display: none !important;
}

.ai-analysis-content td:empty,
.ai-result-html td:empty {
  display: none !important;
}

/* 处理只包含空白的行 */
.ai-analysis-content tr:has(td:not(:empty)):not(:has(td:not(:empty:not(:blank)))),
.ai-result-html tr:has(td:not(:empty)):not(:has(td:not(:empty:not(:blank)))) {
  display: none !important;
}

/* 暗主题表格样式 - 使用更强的选择器 */
:deep(.dark) table,
:deep(.dark) .overflow-x-auto table {
  background: transparent !important;
}

:deep(.dark) table th,
:deep(.dark) table td,
:deep(.dark) .overflow-x-auto table th,
:deep(.dark) .overflow-x-auto table td {
  border: 1px solid rgba(168, 85, 247, 0.3) !important;
  vertical-align: top !important;
  background: rgba(30, 41, 59, 0.8) !important;
  color: #e5e7eb !important;
  padding: 8px 12px !important;
}

:deep(.dark) table th,
:deep(.dark) .overflow-x-auto table th {
  background: rgba(168, 85, 247, 0.2) !important;
  font-weight: 600 !important;
  color: #c084fc !important;
}

:deep(.dark) table tr:hover td,
:deep(.dark) .overflow-x-auto table tr:hover td {
  background: rgba(168, 85, 247, 0.15) !important;
  color: #ffffff !important;
}

/* 亮主题表格样式 */
table th,
table td {
  border: 1px solid rgba(168, 85, 247, 0.15) !important;
  vertical-align: top !important;
  background: #ffffff !important;
  color: #374151 !important;
  padding: 8px 12px !important;
}

table th {
  background: rgba(168, 85, 247, 0.08) !important;
  font-weight: 600 !important;
  color: #7c3aed !important;
}

table tr:hover td {
  background: rgba(168, 85, 247, 0.03) !important;
  color: #111827 !important;
}

/* Electric color for AI loading */
.text-electric-500 {
  color: #00f5ff;
}

/* Cyber按钮样式 */
.cyber-button-sm {
  background: linear-gradient(135deg, rgba(0, 224, 198, 0.2), rgba(0, 245, 255, 0.2));
  border: 1px solid rgba(0, 245, 255, 0.4);
  color: #00f5ff;
  padding: 0.25rem 0.5rem;
  border-radius: 6px;
  font-size: 0.75rem;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
}

.cyber-button-sm:hover {
  background: linear-gradient(135deg, rgba(0, 224, 198, 0.3), rgba(0, 245, 255, 0.3));
  box-shadow: 0 0 12px rgba(0, 245, 255, 0.3);
}

/* AI分析结果样式 */
.ai-result {
  line-height: 1.6;
}

/* AI分析结果标题 - 暗主题 */
.dark .ai-result h1,
.dark .ai-result h2,
.dark .ai-result h3 {
  color: #a855f7;
  margin: 1rem 0 0.5rem 0;
}

.dark .ai-result p {
  margin: 0.5rem 0;
  color: #e5e7eb;
}

/* AI分析结果标题 - 亮主题 */
.ai-result h1,
.ai-result h2,
.ai-result h3 {
  color: #7c3aed;
  margin: 1rem 0 0.5rem 0;
}

.ai-result p {
  margin: 0.5rem 0;
  color: #374151;
}

.ai-result ul,
.ai-result ol {
  margin: 0.5rem 0;
  padding-left: 1.5rem;
}

.ai-result li {
  margin: 0.25rem 0;
}

/* 美化 markdown 表格 - 暗主题 */
.ai-analysis-content table,
.ai-result-html table {
  width: 100% !important;
  border-collapse: collapse !important;
  margin: 1rem 0 !important;
  background: transparent !important;
  border: 2px solid rgba(168, 85, 247, 0.4) !important;
}

.dark .ai-analysis-content table,
.dark .ai-result-html table {
  border: 2px solid rgba(168, 85, 247, 0.5) !important;
}

.ai-analysis-content th, 
.ai-analysis-content td,
.ai-result-html th,
.ai-result-html td {
  border: 1px solid rgba(168, 85, 247, 0.3) !important;
  padding: 0.75rem 1rem !important;
  text-align: left !important;
}

/* 暗主题表格单元格 */
.dark .ai-analysis-content th,
.dark .ai-result-html th {
  background: rgba(168, 85, 247, 0.25) !important;
  color: #c084fc !important;
  font-weight: 600 !important;
  border: 1px solid rgba(168, 85, 247, 0.5) !important;
}

.dark .ai-analysis-content td,
.dark .ai-result-html td {
  color: #e5e7eb !important;
  background: rgba(30, 41, 59, 0.7) !important;
  border: 1px solid rgba(168, 85, 247, 0.4) !important;
}

.dark .ai-analysis-content tr:nth-child(even) td,
.dark .ai-result-html tr:nth-child(even) td {
  background: rgba(168, 85, 247, 0.15) !important;
}

.dark .ai-analysis-content tr:hover td,
.dark .ai-result-html tr:hover td {
  background: rgba(168, 85, 247, 0.2) !important;
}

/* 亮主题表格单元格 */
.ai-analysis-content th,
.ai-result-html th {
  background: rgba(168, 85, 247, 0.15) !important;
  color: #7c3aed !important;
  font-weight: 600 !important;
  border: 1px solid rgba(168, 85, 247, 0.4) !important;
}

.ai-analysis-content td,
.ai-result-html td {
  color: #374151 !important;
  background: #ffffff !important;
  border: 1px solid rgba(168, 85, 247, 0.3) !important;
}

.ai-analysis-content tr:nth-child(even) td,
.ai-result-html tr:nth-child(even) td {
  background: rgba(168, 85, 247, 0.05) !important;
}

.ai-analysis-content tr:hover td,
.ai-result-html tr:hover td {
  background: rgba(168, 85, 247, 0.12) !important;
}
</style>
